/**
 *  createc by jsq on 2017/11/10
 *  2018/12/20优化代码
 */
import React from 'react';
import {Button, Form, Select, Input, Col, Row, Switch, message, Icon} from 'antd';
import {connect} from 'react-redux'
import {messages} from "share/common";
import httpFetch from 'share/httpFetch';
import config from 'config'
import menuRoute from 'routes/menuRoute'
import 'styles/setting/department-group/new-department-group.scss';

const FormItem = Form.Item;
const Option = Select.Option;
import LanguageInput from 'components/template/language-input/language-input';
import deptGroupService from "./dept-group.service";

class NewDepartmentGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      statusCode: messages('common.enabled'), /*启用*/
      record: {
        deptGroupCode: "",
        i18n: {}, //描述的多语言
        name: '',
        enabled: true,
      },
    };
  }

  componentWillMount() {
    let id = this.props.params.id;
    if(id){
      deptGroupService.getDeptGroupById(id).then((response) => {
        if (response.status === 200) {
          this.setState({
            record: response.data
          })
        }
      });
    }

  }


  //新建预算表
  handleSave = (e) => {
    e.preventDefault();
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({loading: true});
        let params = Object.assign(record, values);
        httpFetch.post(`${config.baseUrl}/api/DepartmentGroup/insertOrUpdate`, params).then((response) => {
          if (response) {
            message.success(messages('setting.key256'/*保存成功！*/));
            let url = menuRoute.getMenuItemByAttr('department-group', 'key').children.departmentGroupDetail.url;
            url = url.replace(':id', response.data.id);
            this.context.router.push(url)
          }
        }).catch((e) => {
          if (e.response) {
            message.error(`${messages('common.save.filed')}, ${e.response.data.message}`);
          }
          this.setState({loading: false});
        })
      }
    });
  };

  //点击取消，返回部门组
  handleCancel = (e) => {
    e.preventDefault();
    this.context.router.push(menuRoute.getMenuItemByAttr('department-group', 'key').url);
  };

  handleChange = () => {
    if (this.state.loading) {
      this.setState({
        loading: false
      })
    }
  };

  //描述多语言
  handleDescriptionChange = (value, i18nName) => {
    let record = this.state.record;
    record.name = value;
    record.i18n.name = i18nName;
    this.setState({record})
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {statusCode, loading, record} = this.state;
    const {id} = this.props.params;
    return (
      <div className="new-department-group">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('setting.key478'/*部门组代码*/)}
                colon={true}>
                {getFieldDecorator('deptGroupCode', {
                  initialValue: record.deptGroupCode,
                  rules: [
                    {required: true, message: messages('common.please.enter')},
                    //部门组代码前端不做校验，使用后端提示
                  ]
                })(
                  <Input placeholder={messages('common.please.enter')} disabled={id}/>)
                }
              </FormItem>
              <div className="department-group-tips">
                {messages('setting.key483'/*注：部门组代码保存后将不可修改*/)}
              </div>
            </Col>
            <Col span={8} offset={1}>
              <FormItem
                label={<span><span style={{color: 'red'}}>*</span>&nbsp;{messages('setting.key479'/*部门组名称*/)}</span>}
                colon={true}>
                  <LanguageInput nameChange={this.handleDescriptionChange}
                                 name={record.name}
                                 isEdit={id}
                                 i18nName={record.i18n.name || null}/>
              </FormItem>
            </Col>
            <Col span={6} offset={1}>
              <FormItem
                label={messages('common.status', {status: statusCode})}
                colon={false}>
                {getFieldDecorator("enabled", {
                  initialValue: record.enabled,
                  valuePropName: 'checked',
                  rules: [
                    {
                      validator: (item, value, callback) => {
                        this.setState({
                          statusCode: value ? messages('common.enabled') /*启用*/
                            : messages('common.disabled') /*禁用*/
                        });
                        callback();
                      }
                    }
                  ],
                })
                (<Switch checkedChildren={<Icon type="check"/>}
                         unCheckedChildren={<Icon type="cross"/>}/>)
                }
              </FormItem>
            </Col>
          </Row>
          <Button type="primary" loading={loading} htmlType="submit">
            {messages('common.save') /*保存*/}
          </Button>
          <Button onClick={this.handleCancel} style={{marginLeft: 8}}>
            {messages('common.cancel') /*取消*/}
          </Button>
        </Form>
      </div>
    )
  }
}

NewDepartmentGroup.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}


const WrappedNewDepartmentGroup = Form.create()(NewDepartmentGroup);

export default connect(mapStateToProps)(WrappedNewDepartmentGroup);
